﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MementoClient.Interfaces;
using MementoLibrary.DTOs;
using MementoClient.ViewModels;
using System.Threading.Tasks;
using RestSharp;
using System.Configuration;

namespace MementoClient.Classes
{
    public class DataRepository : IDataRepository
    {
        private readonly IUserTasksRetriever userTasksRetriever;
        private readonly IGetAsyncService getAsyncService;
        private RestClient restClient;

        public DataRepository(IUserTasksRetriever userTasksRetriever, IGetAsyncService getAsyncService)
        {
            var serverUrl = ConfigurationManager.AppSettings["MementoServerUrl"];

            this.userTasksRetriever = userTasksRetriever;
            this.getAsyncService = getAsyncService;
            this.restClient = new RestClient(serverUrl);
        }

        private Task<IEnumerable<CategoryGroupDTO>> GetCategoryGroups()
        {
            return getAsyncService.GetAsync<IEnumerable<CategoryGroupDTO>>("api/categorygroup");
        }

        public Task<IEnumerable<WorkLogDTO>> GetWorklogsForUser(DateTime from, DateTime to)
        {
            return getAsyncService.GetAsync<IEnumerable<WorkLogDTO>>(string.Format("api/worklog/?from={0}&to={1}", from.ToLongDateString(), to.ToLongDateString()));
        }

        public void GetCategoryGroups(Action<IEnumerable<CategoryGroupDTO>> callback)
        {
            Task.Factory.StartNew(() =>
                {
                    var categoryGroupsTask = getAsyncService.GetAsync<IEnumerable<CategoryGroupDTO>>("api/categorygroup");
                    categoryGroupsTask.ContinueWith(a =>
                    {
                        callback(a.Result);
                    });
                });
        }

        public void GetClientData(DateTime from, DateTime to, string userName, Action<ClientDataContainer> callback)
        {
            Task.Factory.StartNew(() =>
                                      {
                                          var categoryGroupsTask = GetCategoryGroups();
                                          var worklogsTask = GetWorklogsForUser(from, to);
                                          var tasksForUserTask = Task.Factory.StartNew(
                                              () => userTasksRetriever.GetTasksForUser(userName)
                                              );
                                          Task.WaitAll(categoryGroupsTask, worklogsTask, tasksForUserTask);
                                          callback(new ClientDataContainer() { CategoryGroups = categoryGroupsTask.Result, WorkLogs = worklogsTask.Result, Tasks = tasksForUserTask.Result });
                                      });
        }

        /// <summary>
        /// Need to get rid of this method and consolidate with the GetWorkLogsForUser method once the UI is fully asynchronous
        /// </summary>
        /// <returns></returns>
        public List<WorkLogDTO> GetWorkLogs()
        {
            return new List<WorkLogDTO>
            {
                new WorkLogDTO(){
                    Task = new TaskDTO{Name="Task 1", Description="Task description"},
                    Minutes=20,
                    Workdate=DateTime.Now
                }
            };
        }

        public void SaveWorkLog(WorkLogDTO workLog)
        {
            RestRequest request = new RestRequest("api/worklog/put", Method.PUT);
            //request.AddHeader("Accept", "application/xml");
            //request.RequestFormat = DataFormat.Json
            //request.AddBody(
            request.AddParameter("subject", "Testint POST");
            request.AddUrlSegment("id", "5");
            var response = restClient.Execute(request);
        }

        public IEnumerable<MementoClientConnectorInterfaces.Task> GetTasksForUser(string userName)
        {
            return userTasksRetriever.GetTasksForUser(userName);
        }

    }
}
